package com.xrui.hbaseview.system;

import java.util.Arrays;
import java.util.regex.Pattern;

public class Version implements Comparable<Version> {

    //region Constants
    private static final Pattern DELIMITER = Pattern.compile("\\.");
    //endregion

    //region Variables
    private int[] version;
    //endregion

    public Version(String version) {
        String[] parts = DELIMITER.split(version);
        if (parts.length < 2 && parts.length > 4) {
            throw new IllegalArgumentException(String.format("incorrect version format: %s", version));
        }

        this.version = new int[]{0, 0, 0, 0};
        for (int i = 0; i < parts.length; i++) {
            this.version[i] = Integer.parseInt(parts[i]);
        }
    }

    //region Public Methods
    public static int compare(String ver1, String ver2) {
        Version version1 = new Version(ver1);
        Version version2 = new Version(ver2);

        return version1.compareTo(version2);
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Version &&
            Arrays.equals(version, ((Version) obj).version);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(version);
    }

    @Override
    public int compareTo(Version o) {
        for (int i = 0; i < version.length && i < o.version.length; i++) {
            if (version[i] != o.version[i]) {
                return version[i] - o.version[i];
            }
        }
        return 0;
    }
    //endregion
}
